package com.hrt.kuducode;

import org.apache.kudu.ColumnSchema;
import org.apache.kudu.Schema;
import org.apache.kudu.Type;
import org.apache.kudu.client.CreateTableOptions;
import org.apache.kudu.client.KuduClient;
import org.apache.kudu.client.KuduException;
import org.apache.kudu.client.PartialRow;
import java.util.Arrays;

/**
 * kudu的分区操作
 */
public class KuduPartition {
    public static void main(String[] args) throws KuduException {
        KuduClient client = new KuduClient.KuduClientBuilder("cm1:7051,cm2:7051,cm3:7051").build();

        //创建表 kudu_t2
        if(!client.tableExists("kudu_t3")){
            //指定表中的各个列信息
            Schema schema = new Schema(Arrays.asList(
                    new ColumnSchema.ColumnSchemaBuilder("id", Type.INT32).key(true).build(),
                    new ColumnSchema.ColumnSchemaBuilder("name", Type.STRING).build(),
                    new ColumnSchema.ColumnSchemaBuilder("age", Type.INT32).build(),
                    new ColumnSchema.ColumnSchemaBuilder("score", Type.DOUBLE).build()
            ));
            //设置表的分区规则 --指定hash分区
//            CreateTableOptions options = new CreateTableOptions();
//            options.addHashPartitions(Arrays.asList("id"), 5);


            //设置range范围分区
//            CreateTableOptions options = new CreateTableOptions();
//            options.setRangePartitionColumns(Arrays.asList("id"));
//            int flag = 0;
//            for(int i =0 ;i<5;i++){
//                PartialRow lower = schema.newPartialRow();
//                lower.addInt("id", flag);
//                flag+=10;
//                PartialRow upper = schema.newPartialRow();
//                upper.addInt("id", flag);
//                options.addRangePartition(lower,upper );
//            }

            //设置hash + range范围 分区
            CreateTableOptions options = new CreateTableOptions();
            options.addHashPartitions(Arrays.asList("id"), 5);
            options.setRangePartitionColumns(Arrays.asList("id"));
            int flag = 0;
            for(int i =0 ;i<5;i++){
                PartialRow lower = schema.newPartialRow();
                lower.addInt("id", flag);
                flag+=10;
                PartialRow upper = schema.newPartialRow();
                upper.addInt("id", flag);
                options.addRangePartition(lower,upper );
            }


            client.createTable("kudu_t3", schema, options);
        }
        client.close();
    }
}
